using UnityEngine;
using System.Collections;
using Entities;

public class PlayerMove : MonoBehaviour {
	
	
	public float moveSpeed;
	public Vector3 targetPosition;
	private Vector3 startingPosition;
	private CharacterController controller;
	private Vector3 dir;
		
	// Use this for initialization
	void Start () {
		controller = (CharacterController) GetComponent("CharacterController");
		//target = transform.localPosition;
		//startingPosition = transform.position;
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Mouse0)){
	        // create a logical horizontal plane at the player position:
	        Plane playerPlane = new Plane(Vector3.up, transform.position);
	        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	        float hitdist = 0.0f;
	        // find point clicked in the plane (if any):
	        if (playerPlane.Raycast(ray, out hitdist)) {
	            // update targetPosition to the clicked point: 
	            targetPosition = ray.GetPoint(hitdist);
	            dir = targetPosition - transform.position;
	            dir.y = 0; // keep only the horizontal direction
				dir.Normalize();
				transform.localRotation = Quaternion.LookRotation(dir);
	        }
	    }
		Vector3 target = new Vector3(targetPosition.x, 0 , targetPosition.z);
		Vector3 position = new Vector3(transform.position.x, 0 , transform.position.z);
		if (Vector3.Distance(target, position) > moveSpeed * Time.deltaTime){
	    	controller.SimpleMove(dir * moveSpeed);
		}
	}
}
